import numpy as np
import pymysql
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics.pairwise import cosine_similarity
from operator import itemgetter

class ItemBasedCF:
    def __init__(self):
        self.db_config = {
            'host': '127.0.0.1',
            'user': 'root',
            'password': '1234',
            'port': 3306,
            'database': 'flask_job',
            'charset': 'utf8'
        }

    def _get_db_connection(self):
        return pymysql.connect(**self.db_config)

    def get_item_data(self):
        conn = self._get_db_connection()
        try:
            with conn.cursor() as cursor:
                cursor.execute(
                    'SELECT id, difficulty, score_avg, click_count, visit_count FROM tb_item'
                )
                return cursor.fetchall()
        finally:
            conn.close()

    def normalize_features(self, items):
        features = np.array([[item[1], item[2], item[3], item[4]] for item in items])
        scaler = MinMaxScaler()
        return scaler.fit_transform(features)

    def calculate_item_similarity(self):
        items = self.get_item_data()
        normalized_features = self.normalize_features(items)
        cosine_sim = cosine_similarity(normalized_features)
        return cosine_sim, items

    def recommend_all_items(self, cosine_sim, items, top_n=5):
        """对所有物品计算推荐列表"""
        recommendations = {}
        for item in items:
            item_id = item[0]
            recommended = self.recommend_items(item_id, cosine_sim, items, top_n)
            recommendations[item_id] = recommended
        return recommendations

if __name__ == "__main__":
    cf = ItemBasedCF()
    try:
        cosine_sim, items = cf.calculate_item_similarity()
        all_recommendations = cf.recommend_all_items(cosine_sim, items, top_n=3)

        # 打印部分结果（例如前5个物品的推荐）
        for item_id, recommended in list(all_recommendations.items())[:5]:
            print(f"物品 {item_id} 的推荐列表：")
            for rec in recommended:
                print(f"  - 推荐物品ID: {rec[0]}")
    except Exception as e:
        print(f"Error: {str(e)}")